package cn.crc.udp;

public class HexUtil {
    public static String byteToHex(byte[] bytes){
        StringBuilder sb = new StringBuilder();
        for(byte b:bytes){
            sb.append(String.format("%02X",b));
        }
        return sb.toString();
    }

    public static byte[] hexToByte(String hex){
        int len = hex.length();
        byte[] bytes = new byte[len /2];
        for(int i=0;i<len;i += 2){
            bytes[i /2]=(byte)((Character.digit(hex.charAt(i),16)<<4)
                    + Character.digit(hex.charAt(i +1),16));
        }
        return bytes;
    }
    public static String hexToTxt(String txt){
        return new String(hexToByte(txt));
    }

    public static void main(String[] args) {
        String txtSource= "ABC123恭喜发财";
        String txtHex= byteToHex(txtSource.getBytes());
        System.out.println("16进制-"+txtHex);
        String txt汉字= new String(hexToTxt(txtHex));
        System.out.println("还原后-"+txt汉字);

        String[] arr1= {"上海","北京","广州"};
        String arrHex= byteToHex(arr1.toString().getBytes());
        System.out.println("16进制:-"+arrHex);
        String arr汉字= new String(hexToTxt(arrHex));
        System.out.println("还原后:"+arr汉字);
    }

}
